package deployment

import (
	"context"
	"github.com/gin-gonic/gin"
	"k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8sapi/core"
	"k8sapi/lib"
)

func RegHandlers(r *gin.Engine){
	r.POST("/update/deployment/scale",incrReplicas)
	r.POST("/core/deployments",ListAllDeployments)
	r.POST("/core/pods",ListPodsByDeployment)
	r.GET("/core/pods_json",GetJsonByPod)
	r.DELETE("/core/pods",DeltePOD)
	r.POST("/create/deployments",CreateDeploymentHandler)
	r.DELETE("/update/deployment",DeleteDeployment)
}
//根据ns和name删除deployment
func DeleteDeployment(c *gin.Context) {
	ns:=c.DefaultQuery("namespaces","default")
	depname:=c.DefaultQuery("deployment","")
	if ns=="" || depname=="" {
		panic("deployment or ns error")
	}
	lib.CheckError(DelDeployment(ns,depname))
	c.JSON(200,gin.H{"message":"ok","result":DelDeployment(ns,depname)})
}
//根据ns 获取所有deployment
func ListAllDeployments(c *gin.Context){
	ns:=c.DefaultQuery("namespace","default")
	c.JSON(200,gin.H{"message":"Ok","result":ListAll(ns)})
}
//根据 deployment名称 获取 pod列表
func ListPodsByDeployment(c *gin.Context){
	ns:=c.DefaultQuery("namespace","default")
	depname:=c.DefaultQuery("deployment","default")
	dep,err:=core.DepMap.GetDeployment(ns,depname)
	lib.CheckError(err)
	rslist,err:=core.RsMap.ListByNameSpace(ns)  // 根据namespace 取到 所有rs
	lib.CheckError(err)
	labels,err:=GetRsLableByDeployment_ListWatch(dep,rslist) //根据deployment过滤出 rs，然后直接获取标签
	lib.CheckError(err)
	c.JSON(200,gin.H{"message":"Ok","result":ListPodsByLabel(ns,labels)})
}
func ListEvent(c *gin.Context) {

}
//增加或减少副本数
func incrReplicas(c *gin.Context){
		req:= struct {
			Namespace string `json:"ns" binding:"required,min=1"`
			Deployment string `json:"deployment" binding:"required,min=1"`
			Dec bool `json:"dec"` //是否减少一个
		}{}
		lib.CheckError(c.ShouldBindJSON(&req))

		ctx:=context.Background()
		scale,err:=lib.K8sClient.AppsV1().Deployments(req.Namespace).
			GetScale(ctx,req.Deployment,v1.GetOptions{})
		lib.CheckError(err)
	    if req.Dec{ //dec==true代表是减少副本数
	    	scale.Spec.Replicas--
		}else{
	    	 scale.Spec.Replicas++
		}
	_,err=lib.K8sClient.AppsV1().Deployments(req.Namespace).
			UpdateScale(ctx,req.Deployment,scale,v1.UpdateOptions{})
	lib.CheckError(err)
	lib.Sunccess("Ok",c)
}

//根据Namespace和Pod获取Pod的Json
func GetJsonByPod(c *gin.Context) {
	ns:=c.DefaultQuery("namespace","default")
	podName:=c.DefaultQuery("pod","")
	if podName==""||ns==""{
		panic("error pod or namespace")
	}
	if pod:=core.PodMap.Get(ns,podName);pod==nil{
		panic("no such pod "+ podName)
	}else{
		c.JSON(200,pod)
	}
}
//删除Pod
func DeltePOD(c *gin.Context) {
	ns:=c.DefaultQuery("namespace","default")
	podName:=c.DefaultQuery("pod","")
	if podName==""||ns==""{
		panic("error pod or ns")
	}
	lib.CheckError(DeletePod(ns,podName))
	c.JSON(200,gin.H{"message":"OK"})
}
func CreateDeploymentHandler(c *gin.Context) {
	depReq:=&DeploymentRequest{}
	lib.CheckError(c.ShouldBind(depReq))
	lib.CheckError(CreateDeployment(depReq))
	c.Redirect(301,"/deployments")
}
